<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@include file="../common/common.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/static/css/page.css">

    <title> <spring:message code="class.page.title"/></title>

    <script type="text/javascript">
        var _gridWidth;
        var _gridHeight;
        //页面自适应
        function resizePageSize(){
            _gridWidth = $(document).width()-12;/*  -189 是去掉左侧 菜单的宽度，   -12 是防止浏览器缩小页面 出现滚动条 恢复页面时  折行的问题 */
            _gridHeight = $(document).height()-32-80; /* -32 顶部主菜单高度，   -90 查询条件高度*/
        }

        $(function()
        {
            var addFileNameId = $( "#add-file-name-id" ),
                addFilePathId = $( "#add-file-path-id" ),
                allFields = $( [] ).add( addFileNameId ).add( addFilePathId );

            resizePageSize();
            $("#file-add-btn-id").click(function (evnent) {
                $("#add-file-form-id").resetForm();
                $("#add-file-dialog-id").dialog('open');
            });
            $("#file-delete-btn-id").click(function (evnent) {
                checkEnter1();
            });
            $("#file-download-btn-id").click(function (evnent) {
                checkEnter2();
            });
            $("#file-copy-btn-id").click(function (evnent) {
                checkEnter3();
            });
            $("#add-file-dialog-id").dialog({
                    autoOpen : false,
                    width : 400,
                    height : 300,
                    modal : true,
                    resizable : false,
                    title: "<spring:message code='file.add'/>",
                    buttons: [
                        {
                            text: "<spring:message code='common.confirm'/>",
                            click: function() {
                                var bValid = true;
                                allFields.removeClass( "ui-state-error" );

                                // bValid = bValid && checkLength( addFileNameId, 1, 256 );
                                bValid = bValid && checkLength( addFilePathId,  1, 256 );
                                if ( !bValid ) {
                                    return;
                                }
                                $("#add-file-form-id").submit();

                            }
                        },
                        {
                            text: "<spring:message code='common.cancel'/>",
                            click: function() {
                                $( this ).dialog( "close" );
                            }
                        }
                    ]
                }
            );
            $("#add-file-form-id").ajaxForm(
                {
                    dataType: "json",
                    success : function(data) {
                        $("#add-file-dialog-id").dialog( "close" );
                        message(data.msg);
                        $("#flexiGridID").flexReload();
                    },
                    error : function() {
                        message("<spring:message code='common.error'/>");
                    }
                }
            );

            var _columnWidth= (_gridWidth-150)/10;
            $("#flexiGridID").flexigrid({
                width : _gridWidth,
                height : _gridHeight,
                url : "${pageContext.request.contextPath}/file/getFileInfolist",
                dataType : 'json',
                colModel : [
                    {display : "<spring:message code='file.name'/>",name : 'objectKey',width : _columnWidth*3, sortable : false,align : 'center'},
                    {display : "<spring:message code='file.content.length'/>",name : 'contentLength',width : _columnWidth*3, sortable : false,align : 'center'},
                    {display : "<spring:message code='file.modify.time'/>",name : 'lastModified',width : _columnWidth*3, sortable : false,align : 'center'},
                    <%--{display : "<spring:message code='file.operation'/>",name : 'objectKey',width : _columnWidth, sortable : true,align : 'center',process: function(v,_trid,_row) {--%>
                    <%--        var htmlContents ='<a style="color:blue;cursor:pointer;" href="${pageContext.request.contextPath}/file/download/'+_row.objectKey+ '" target="_blank"><spring:message code="file.download"/></a>';--%>
                    <%--        return htmlContents;--%>
                    <%--    }},--%>
                    <%--{display : "<spring:message code='file.operation'/>",name : 'objectKey',width : _columnWidth, sortable : true,align : 'center',process: function(v,_trid,_row) {--%>
                    <%--        var htmlContents ='<span style="color:blue;cursor:pointer;" onclick="deleteObject(\''+_row.objectKey+'\');"><spring:message code='file.delete'/></span>';--%>
                    <%--        return htmlContents;--%>
                    <%--    }}--%>
                    {display : "<spring:message code='file.operation'/>",name : 'objectKey',width : _columnWidth, sortable : true,align : 'center',process: function(v,_trid,_row) {
                            var htmlContents ='<span style="color:blue;cursor:pointer;" onclick="previewObject(\''+_row.objectKey+'\');"><spring:message code='file.preview'/></span>';
                            return htmlContents;
                        }}

                ],
                resizable : false, //resizable table是否可伸缩
                useRp : true,
                usepager : false, //是否分页
                autoload : false, //自动加载，即第一次发起ajax请求
                hideOnSubmit : true, //是否在回调时显示遮盖
                showcheckbox : true, //是否显示多选框
                //rowhandler : rowDbclick, //是否启用行的扩展事情功能,在生成行时绑定事件，如双击，右键等
                rowbinddata : true,
                numCheckBoxTitle : "<spring:message code='common.selectall'/>"
            });
            query();

        });
        function query(param1){
            $('#flexiGridID').flexOptions({
                newp: 1,
                extParam: param1||[]
            }).flexReload();
        }
        function deleteObject(objectKey) {//删除组件
            console.log(objectKey);
            $.ajax({
                type : 'POST',
                url : '${pageContext.request.contextPath}/file/delete/'+objectKey+'',
                dataType : 'json',
                cache : false,
                data : {},
                success : function(data) {
                    message("<spring:message code='file.delete.success'/>");
                    $("#flexiGridID").flexReload();
                },
                error : function() {
                    message("<spring:message code='file.delete.fail'/>");
                }
            });
        }
        function downloadObject(objectKey) {//下载组件
            // console.log(objectKey);
            document.location.href = "${pageContext.request.contextPath}/file/download/"+objectKey;
        }
        function addfolderObject(objectKey) {//下载组件
            // console.log(objectKey);
            document.location.href = "${pageContext.request.contextPath}/file/addfolder/"+objectKey;
        }
        function copyObject(objectKey) {
            console.log(objectKey);
            $.ajax({
                type : 'POST',
                url : '${pageContext.request.contextPath}/file/copy/'+objectKey+'',
                dataType : 'json',
                cache : false,
                data : {},
                success : function(data) {
                    message("<spring:message code='file.copy.success'/>");
                    $("#flexiGridID").flexReload();
                },
                error : function() {
                    message("<spring:message code='common.error'/>");
                }
            });
        }

        function checkEnter1() {
            var selectedData = [];
            selectedData = $("#flexiGridID").getCheckedRows();
            //获取选中行数量
            //var x = jQuery('#flexiGridID .trSelected').length;
            //获取选中行文件名
            jQuery('#flexiGridID .trSelected').each(function(i,item){
                //alert(jQuery(item).children().eq(1).text());
                var objectKey = jQuery(item).children().eq(1).text();
                deleteObject(objectKey);
            });
        }
        function checkEnter2() {
            var selectedData = [];
            selectedData = $("#flexiGridID").getCheckedRows();
            //获取选中行数量
            //var x = jQuery('#flexiGridID .trSelected').length;
            //获取选中行文件名
            jQuery('#flexiGridID .trSelected').each(function(i,item){
                //alert(jQuery(item).children().eq(1).text());
                var objectKey = jQuery(item).children().eq(1).text();
                downloadObject(objectKey);
            });
        }
        function checkEnter3() {
            var selectedData = [];
            selectedData = $("#flexiGridID").getCheckedRows();
            //获取选中行数量
            //var x = jQuery('#flexiGridID .trSelected').length;
            //获取选中行文件名
            jQuery('#flexiGridID .trSelected').each(function (i, item) {
                //alert(jQuery(item).children().eq(1).text());
                var objectKey = jQuery(item).children().eq(1).text();
                copyObject(objectKey);
            });
        }

        //[Liu]预览主函数
        function previewObject(objectKey) {
            console.log("[Liu Debug]预览文件~previewObject:objectKey="+objectKey);
            console.log();
            $.ajax({
                type : 'POST',
                url : '${pageContext.request.contextPath}/file/preview/'+objectKey+'',
                dataType : 'json',
                cache : false,
                data : {},
                success : function(data) {
                    console.log("[Liu Debug]预览文件~previewObject:objectKey="+objectKey);
                    initPreviewWindow(data.id,data.msg);
                    setCurrentPreviewMode(judgeFileTypeBySuffix(getFileSuffix(objectKey)),data.tempUrl);
                    openPreview();//打开预览窗口

                    $("#flexiGridID").flexReload();
                },
                error : function() {
                    message("<spring:message code='common.error'/>");
                },

            });
        }

        //[Liu]初始化预览窗口
        function initPreviewWindow(key,msg) {
            $("#previewInfo").html("文件ID："+key+"+文件信息："+msg);
        }

        //[Liu]隐藏所有的预览Div
        function hideAllPreviewDiv() {
            document.getElementById("previewImage").style.display="none";
            document.getElementById("previewAudio").style.display="none";
            document.getElementById("previewVideo").style.display="none";
            document.getElementById("previewDoc").style.display="none";
            document.getElementById("previewText").style.display="none";
            document.getElementById("previewUnknown").style.display="none";
        }


        //[Liu]选择正确的预览模式
        function setCurrentPreviewMode(type,path) {
            hideAllPreviewDiv();
            switch (type) {
                case "img":
                    $('#previewImage').css("display","block");
                    $('#preImageSrc').attr("src",path)
                    break;
                case "audio":
                    $('#previewAudio').css("display","block");
                    $('#preAudioSrc').attr("src",path)
                    break;
                case "video":
                    $('#previewVideo').css("display","block");
                    $('#preVideoSrc').attr("src",path)
                    break;
                case "office":
                    $('#preDocSrc').attr("src","https://view.xdocin.com/xdoc?_xdoc="+fixUrlAndSymbolToUtf(path));
                    // $('#preDocSrc').attr("src","https://view.officeapps.live.com/op/view.aspx?src="+fixUrlAndSymbolToUtf(path));
                    $('#previewDoc').css("display","block");
                    break;
                case "text":
                    $('#previewText').css("display","block");
                    //[Liu]报错：被CORS配置阻挡，无法访问
                    //[Liu]好像是因为JS没法跨域抓取HTML
                    //[Liu]Access to XMLHttpRequest at [path] from origin 'https://localhost:8443' has been blocked by CORS policy:
                    //[Liu]No 'Access-Control-Allow-Origin' header is present on the requested resource.
                    // $.get(fixUrlAndSymbolToUtf(path), function(data){
                    //     alert("Data Loaded: " + data);
                    // });
                    // $('#preTextSrc').val(data);
                    $('#preTextSrc').attr("src","https://view.xdocin.com/xdoc?_xdoc="+fixUrlAndSymbolToUtf(path));


                    break;
                case "unknown":
                    $('#previewUnknown').css("display","block");
                    break;
                default:

            }
        }

        //[Liu]修正URL中的&符号为%26
        function fixUrlAndSymbolToUtf(url) {
            let fixUrl=url.replace(/&Expires/, "%26Expires");
            fixUrl=fixUrl.replace(/&Signature/, "%26Signature");
            console.log("[Liu Debug]修正URL格式中的&符号~fixUrlAndSymbolToUtf:修改后url="+fixUrl);
            return fixUrl;
        }

        //[Liu]获取后缀
        function getFileSuffix(path) {
            var index= path.lastIndexOf(".");
            var suffix = path.substr(index+1);
            console.log("[Liu Debug]获取后缀~getFileSuffix:path="+path);
            console.log("[Liu Debug]获取后缀~getFileSuffix:suffix="+suffix);
            return suffix;
        }

        //[Liu]判断文件类型
        function judgeFileTypeBySuffix(suffix) {
            let result = "unknown";
            let imgType = ["jpg","jpeg","bmp","png"];
            let audioType = ["mp3","wav","ogg"]
            let videoType = ["mp4","ogg"];
            let officeType = ["doc","docx","ppt","pptx","xsl","xslx"];
            let textType = ["txt","c","cpp","java","py","jsp","html","htm","css","asp","xml"];
            if(imgType.indexOf(suffix.toLowerCase()) !== -1)
                result = "img";
            if(audioType.indexOf(suffix.toLowerCase()) !== -1)
                result = "audio";
            if(videoType.indexOf(suffix.toLowerCase()) !== -1)
                result = "video";
            if(officeType.indexOf(suffix.toLowerCase()) !== -1)
                result = "office";
            if(textType.indexOf(suffix.toLowerCase()) !== -1)
                result = "text";
            console.log("[Liu Debug]判断类型~judgeFileTypeBySuffix:结果="+result);
            return result;
        }

        //[Liu]通过改变Style隐藏预览窗口并停止所有播放
        function closePreview() {
            $("#preAudioSrc")[0].pause();//暂停音乐
            $('#preVideoSrc').get(0).pause();//暂停视频
            //$('video').trigger('pause'); //关闭所有的视频播放
            const preDiv = document.getElementById("previewWindow");
            preDiv.style.display="none";
        }

        //[Liu]通过改变Style展现预览窗口
        function openPreview() {
            const preDiv = document.getElementById("previewWindow");
            preDiv.style.display="block";
        }

    </script>

</head>
<body style="display: flex;flex-direction: column">
<div style="padding-top: 5px;">
    <label><spring:message code="file.name"/>:</label> <input type="text" id="searchRoleName"/>

    <a href="#" id="file-search-btn-id" class="ui-state-default ui-corner-all cbe-button"><span class="ui-icon ui-icon-search"></span><spring:message code="file.search"/></a>
    <a href="#" id="file-delete-btn-id" class="ui-state-default ui-corner-all cbe-button"><span class="ui-icon ui-icon-minusthick"></span><spring:message code="file.delete"/></a>
    <a href="#" id="file-add-btn-id" class="ui-state-default ui-corner-all cbe-button"><span class="ui-icon ui-icon-plus"></span><spring:message code="file.add"/></a>
    <a href="#" id="file-download-btn-id" class="ui-state-default ui-corner-all cbe-button"><span class="ui-icon ui-icon-plus"></span><spring:message code="file.download"/></a>
    <a href="#" id="add-copy-btn-id" class="ui-state-default ui-corner-all cbe-button"><span class="ui-icon ui-icon-plus"></span><spring:message code="file.copy"/></a>
    <a href="#" id="add-folder-btn-id" class="ui-state-default ui-corner-all cbe-button"><span class="ui-icon ui-icon-plus"></span><spring:message code="file.folder"/></a>
</div>
<%--<div>--%>
<%--    <nav  class="navbar-collapse collapse" >--%>
<%--        <ul class="nav navbar-nav fa-ul">--%>
<%--            <li>--%>
<%--                <a id="file-add-btn-id" href="#" class="btn-primary">--%>
<%--                    <i class="glyphicon glyphicon-cloud-upload"> </i>--%>
<%--                    <span><spring:message code="file.add"></spring:message></span>--%>
<%--                </a>--%>
<%--            </li>--%>
<%--            <li><a></a></li>--%>
<%--            <li>--%>
<%--                <a id="file-download-btn-id" href="#" class="btn-primary">--%>
<%--                    <i class="glyphicon glyphicon-cloud-download"> </i>--%>
<%--                    <span><spring:message code="file.download"></spring:message></span>--%>
<%--                </a>--%>
<%--            </li>--%>
<%--            <li><a></a></li>--%>
<%--            <li>--%>
<%--                <a id="add-folder-btn-id" href="#" class="btn-primary">--%>
<%--                    <i class="glyphicon glyphicon-plus"> </i>--%>
<%--                    <span><spring:message code="folder.add"></spring:message></span>--%>
<%--                </a>--%>
<%--            </li>--%>
<%--            <li><a></a></li>--%>
<%--            <li>--%>
<%--                <a id="file-delete-btn-id" href="#" class="btn-primary">--%>
<%--                    <i class="glyphicon glyphicon-trash"> </i>--%>
<%--                    <span><spring:message code="file.delete"></spring:message></span>--%>
<%--                </a>--%>
<%--            </li>--%>
<%--            <li><a></a></li>--%>
<%--            <li>--%>
<%--                <a id="file-search-btn-id" href="#" class="btn-primary">--%>
<%--                    <i class="glyphicon glyphicon-search"> </i>--%>
<%--                    <span><spring:message code="file.search"></spring:message></span>--%>
<%--                </a>--%>
<%--            </li>--%>
<%--            <li><a></a></li>--%>
<%--            <li>--%>
<%--                <a id="file-copy-btn-id" href="#" class="btn-primary">--%>
<%--                    <i class="glyphicon glyphicon-copy"> </i>--%>
<%--                    <span><spring:message code="file.copy"></spring:message></span>--%>
<%--                </a>--%>
<%--            </li>--%>
<%--            <li><a></a></li>--%>
<%--        </ul>--%>
<%--    </nav>--%>
<%--</div>--%>
<table id="flexiGridID" style="display: block;margin: 0px;">

</table>


<div id="add-file-dialog-id" style="display: none">
    <form id="add-file-form-id" action="${pageContext.request.contextPath}/file/addFile" method="post" enctype="application/x-www-form-urlencoded">
<%--        <div class="form-group">--%>
<%--            <span for="add-file-name-id"><spring:message code="file.name"></spring:message></span>--%>
<%--            <input class="form-control" type="text" name="fileName" id="add-file-name-id"/>--%>
<%--        </div>--%>
            <div class="form-group">
                <span for="add-file-name-id"><spring:message code="file.name"></spring:message></span>
                <input class="form-control" type="text" name="fileName" id="add-file-name-id"/>
            </div>
            <div class="form-group">
                <span for="add-file-path-id"><spring:message code="file.choose.name"></spring:message></span>
                <input class="form-control" type="file" name="filePath" id="add-file-path-id"/>
            </div>
        </form>
    </div>
    </form>
</div>

<div id="previewWindow"
     style="
		 	display: none;
			background-color: rgb(255,255,255);
			/*border:1px solid #000;*/
			position: absolute;
			margin: auto;
			top: 0;bottom: 0;left: 0;right: 0;
			width: 1024px;min-height: 25%;
			z-index: 99999;
			/*效果*/
			border-radius: 5px;
			box-shadow: 3px 3px  10px rgb(112,168,211);"
>
    <div id="previewInfo"
         style="height: 25px;background-color: rgb(112,168,211);text-align: center;line-height: 25px;"
    >

    </div>

    <div id="previewImage" align="center">
        <p>图片</p>
        <div id="ImgDiv" style="max-width:inherit ;max-height: inherit;background: lightcoral">
            <img id="preImageSrc" src="" style="width: inherit;height:inherit;object-fit: scale-down">
        </div>

    </div>

    <div id="previewVideo" align="center">
        <p>视频</p>
        <div id="videoDiv" style="width: auto;height: auto;background: lightblue">
            <video id="preVideoSrc" src="" controls="controls" style="width: 100%;height:100%;object-fit: contain">
                您的浏览器不支持 video 标签。
            </video>
        </div>
    </div>

    <div id="previewAudio" style="" align="center">
        <p>音频</p>
        <div id="audioDiv"
             style="margin:0 auto;
				 display:table;">
            <audio id="preAudioSrc" controls>
                您的浏览器不支持 audio 元素。
            </audio>
        </div>
    </div>

    <div id="previewDoc" align="center" style="width: 100%;height: 85%;background: #00CC00">
        <p>Office文档</p>
        <iframe id="preDocSrc" src="" width='100%' height='100%' frameborder='1'>
        </iframe>
    </div>

    <div id="previewText" align="center" style="width: 100%;height: 85%;background: #bf67d7">
        <p>文本</p>
        <iframe id="preTextSrc" src="" width='100%' height='100%'>
        </iframe>
    </div>

    <div id="previewUnknown" align="center">
        <span style="font-size: large;">不支持的文件！</span>
    </div>

    <div id="previewButton"
         align="center";
         style="bottom: 0;
			 height: auto;width: inherit;
			 background: #fdc683;
			 position: absolute;">
        <button onclick="closePreview()">关闭预览</button>
    </div>


</div>

</body>
</html>